<template>
  <div>
    <vxe-button
      status="primary"
      icon="vxe-icon-add"
      size="small"
      content="添加一级分类"
      style="margin-bottom: 20px"
      @click="ShowAdd()"
      v-has="'btn.Category.add'"
    ></vxe-button>
    <vxe-table
      border
      show-overflow
      height="800"
      max-height="800"
      :scroll-y="{ gt: 12 }"
      :row-config="{ keyField: 'id', isHover: true }"
      :tree-config="treeConfig"
      :data="tableData"
    >
      <vxe-column
        type="seq"
        width="60"
        title="序号"
        align="center"
      ></vxe-column>
      <vxe-column field="name" title="分类列表" tree-node></vxe-column>
      <vxe-column width="180" title="操作" align="center">
        <template #default="{ row }">
          <vxe-button
            v-if="row.tier !== 2"
            status="primary"
            icon="vxe-icon-add"
            size="small"
            @click="ShowAdd(row)"
            v-has="'btn.Category.add'"
          ></vxe-button>
          <vxe-button
            status="primary"
            icon="vxe-icon-edit"
            size="small"
            @click="ShowUpdate(row)"
            v-has="'btn.Category.update'"
          ></vxe-button>
          <el-popconfirm
            :title="`确认删除${row.name}吗？`"
            @confirm="DelShow(row)"
          >
            <template #reference>
              <vxe-button
                status="danger"
                icon="vxe-icon-delete-fill"
                size="small"
                v-has="'btn.Category.remove'"
              ></vxe-button>
            </template>
          </el-popconfirm>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
  <vxe-modal
    v-model="isShow"
    width="600"
    show-footer
    @close="resetForm(ruleFormRef)"
  >
    <template #title>
      <span style="color: red">{{
        formData.id ? "修改分类" : "添加分类"
      }}</span>
    </template>
    <el-form
      labelWidth="120px"
      ref="ruleFormRef"
      :model="formData"
      align="center"
      span="24"
      :rules="rules"
    >
      <el-form-item label="分类id：" prop="id">
        <el-input
          :disabled="!formData.document"
          v-model="formData.id"
          placeholder="请输入分类id"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类名称：" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入分类信息"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确认
        </el-button>
      </span>
    </template>
  </vxe-modal>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref } from "vue";
import { useCategoryStore } from "@/stores/category";
import type { FormInstance, FormRules } from "element-plus";
import {
  delCategory1ListApi,
  delCategory2ListApi,
  delCategory3ListApi,
  postCategory1ListApi,
  postCategory2ListApi,
  postCategory3ListApi,
  putCategory1ListApi,
  putCategory2ListApi,
  putCategory3ListApi,
} from "@/api/product/category";
import { ElMessage } from "element-plus";
import { VxeTablePropTypes } from "vxe-table";

// 实例化仓库
const CategoryStore = useCategoryStore();
const ruleFormRef = ref<FormInstance>();
const isShow = ref(false);
// 定义表单数据
const formData = reactive<{
  id: number | null;
  name: string | null;
  categoryId: number | null;
  tier: number; // 确定几级分类
  document: boolean; // 判断是添加还是修改
}>({
  id: null,
  name: null,
  categoryId: null,
  tier: 0,
  document: true,
});
interface RowVO {
  id: number;
  name: string;
  hasChild: boolean;
  tier: number;
  parentId: number | null;
  category1Id: number | null;
  category2Id: number | null;
  category3Id: number | null;
}
const tableData = ref<RowVO[]>([]);
// 获取页面分类数据
const getList = async () => {
  tableData.value = [];
  await CategoryStore.getCategory1ListAction();
  const arr = CategoryStore.category1List;
  arr.map((item) => {
    tableData.value.push({
      id: item.id,
      name: item.name,
      tier: 0,
      hasChild: true,
      parentId: null,
      category1Id: item.id,
      category2Id: null,
      category3Id: null,
    });
  });
  ElMessage({
    message: "获取分类列表成功",
    type: "success",
  });
};
onMounted(async () => {
  await getList();
});
// 列表展开操作
const treeConfig = reactive<VxeTablePropTypes.TreeConfig<RowVO>>({
  lazy: true, // 标识懒加载为true
  transform: true, // 自动将列表转为树结构
  rowField: "id", // 用于 tree-config.transform，树节点的标识字段名
  parentField: "parentId", // 用于 tree-config.transform，树父节点的标识字段名
  hasChild: "hasChild", // 存储是否有子节点的属性
  loadMethod({ row }) { // 用于加载子列表的回调
    // 异步加载子节点
    return fetchChildListApi(row);
  },
});
// 获取二三级分类列表
const fetchChildListApi = async (parentRow: RowVO) => {
  if (parentRow.tier === 0) {// 获取二级列表
    await CategoryStore.getCategory2ListAction(parentRow.id);
    return new Promise<RowVO[]>((resolve) => {
      let childList: RowVO[] = [];
      CategoryStore.category2List.map((item) =>
        childList.push({
          id: item.id + 1000,
          name: item.name,
          hasChild: true, // 有子列表
          tier: 1,
          parentId: item.id,
          category1Id: parentRow.category1Id,
          category2Id: item.id,
          category3Id: null,
        })
      );
      resolve(childList as RowVO[]);
    });
  } else { // 获取三级列表
    await CategoryStore.getCategory3ListAction(parentRow.parentId as number);
    return new Promise<RowVO[]>((resolve) => {
      let childList: RowVO[] = [];
      CategoryStore.category3List.map((item) =>
        childList.push({
          id: item.id + 2000,
          name: item.name,
          hasChild: false, // 没有子列表了
          tier: 2,
          parentId: item.id,
          category1Id: parentRow.category1Id,
          category2Id: parentRow.category2Id,
          category3Id: item.id,
        })
      );
      resolve(childList as RowVO[]);
    });
  }
};
type Row = RowVO | null;
// 添加分类
const ShowAdd = (row: Row = null) => {
  isShow.value = true;
  if (row) {
    if (row.tier === 0) {
      Object.assign(formData, {
        categoryId: row.category1Id,
        id: null,
        name: null,
        tier: 1,
        document: true,
      });
    } else {
      Object.assign(formData, {
        categoryId: row.category2Id,
        id: null,
        name: null,
        tier: 2,
        document: true,
      });
    }
  } else {
    // 清空分类列表数据
    Object.assign(formData, {
      categoryId: null,
      id: null,
      name: null,
      tier: 0,
      document: true,
    });
  }
};
// 修改分类数据
const ShowUpdate = (row: RowVO) => {
  isShow.value = true;
  if (row.tier === 0) {
    Object.assign(formData, {
      categoryId: null,
      id: row.category1Id,
      name: row.name,
      tier: row.tier,
      document: false,
    });
  } else if (row.tier === 1) {
    Object.assign(formData, {
      categoryId: row.category1Id,
      id: row.category2Id,
      name: row.name,
      tier: row.tier,
      document: false,
    });
  } else {
    Object.assign(formData, {
      categoryId: row.category2Id,
      id: row.category3Id,
      name: row.name,
      tier: row.tier,
      document: false,
    });
  }
};
// 删除分类数据
const DelShow = async (row: RowVO) => {
  if (row.tier === 0) {
    await delCategory1ListApi(row.category1Id as number);
  } else if (row.tier === 1) {
    await delCategory2ListApi(row.category2Id as number);
  } else {
    await delCategory3ListApi(row.category3Id as number);
  }
  ElMessage.success("删除成功");
  await getList();
};
// 校验规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  id: [{ required: true, message: "请输入id值", trigger: "blur" }],
});
// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 提交操作，有可能是新增，也有可能是修改
      if (formData.document) {
        if (formData.tier === 0) {
          await postCategory1ListApi({
            id: formData.id as number,
            name: formData.name as string,
          });
        } else if (formData.tier === 1) {
          await postCategory2ListApi({
            category1Id: formData.categoryId as number,
            id: formData.id as number,
            name: formData.name as string,
          });
        } else {
          await postCategory3ListApi({
            category2Id: formData.categoryId as number,
            id: formData.id as number,
            name: formData.name as string,
          });
        }
      } else {
        if (formData.tier === 0) {
          await putCategory1ListApi({
            id: formData.id as number,
            name: formData.name as string,
          });
        } else if (formData.tier === 1) {
          await putCategory2ListApi({
            category1Id: formData.categoryId as number,
            id: formData.id as number,
            name: formData.name as string,
          });
        } else {
          await putCategory3ListApi({
            category2Id: formData.categoryId as number,
            id: formData.id as number,
            name: formData.name as string,
          });
        }
      }
      ElMessage.success("保存成功"); // 提示信息
      isShow.value = false;

      await getList();
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 清除表单验证
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<script lang="ts">
export default {
  name: "CategoryList",
};
</script>
<style scoped></style>
